package com.huiguo.methodargument.exception;

import com.huiguo.methodargument.dto.InvokeResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.net.BindException;

/**
 * @author huiguo
 */
@RestControllerAdvice
@Slf4j
public class MyExceptionHandler {

    /**
     * 参数校验错误拦截处理
     * MethodArgumentNotValidException：Bean 校验异常
     * ConstraintViolationException：方法参数校验异常
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, ConstraintViolationException.class})
    public InvokeResult validationBodyException(Exception exception) {
        log.error("----------->" + exception.getMessage() + ":{}", exception);
        if(exception instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
            String message = methodArgumentNotValidException.getBindingResult().getAllErrors().get(0).getDefaultMessage();
            return InvokeResult.error(message, InvokeResult.TYPE_FAIL_PARAM);
        }
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) exception;
            return InvokeResult.error(constraintViolationException.getConstraintViolations().stream().findFirst().get().getMessage(), InvokeResult.TYPE_FAIL_PARAM);
        }
        return InvokeResult.error("特殊情况","-1");
    }
}
